define(['zepto', 'butterfly/view','../../bsl',
    'text!./audio.html'
], function($, View, bsl, audio) {
    var me = null;

    var view = View.extend({
        gentry: null,
        hl: null,
        le: null,
        er: null,
        ep: null,

        r: null,
        t: 0,
        ri: null,
        rt: null,

        events: {
        	"tap #startRecord":"startRecord",
        	"tap #startPlay" : "startPlay",
        	"tap #cleanHistory" : "cleanHistory",
        	"tap #openDoc" : "OpenDoc",
            "tap #back" : "back",
            "tap .stopPlay" : "stopPlay",

        },
        render: function() {
            me = this;
        },

        onShow: function() {
            this.getDom();
            this.plusReady();
        },

        getDom: function(){
            this.hl = document.getElementById("history");
            this.le = document.getElementById("empty");
            this.er = document.getElementById("record");
            this.rt = document.getElementById("rtime");
            this.ep = document.getElementById("play");
            this.pt = document.getElementById("ptime");
            this.pp = document.getElementById("progress")
            this.ps = document.getElementById("schedule");
        },
        // H5 plus事件处理
        plusReady: function() {
        	var me = this;
            // 获取音频目录对象
            bsl.io.resolveLocalFileSystemURL("_doc/", function(entry) {
                entry.getDirectory("audio", {
                    create: true
                }, function(dir) {
                    gentry = dir;
                    me.updateHistory();
                }, function(e) {
                    console.info("Get directory \"audio\" failed: " + e.message);
                });
            }, function(e) {
                console.info("Resolve \"_doc/\" failed: " + e.message);
            });
        },
         back:function(){
            this.resetback();
        },
        
        OpenDoc : function(e){
           
            window.butterfly.navigate('com.no5.cordovademo/doc/audio', {
                trigger: true
            });
        },

        
 

        // 添加播放项
        createItem: function(entry) {
            var me=this;
            var li = document.createElement("li");
            li.className = "ditem";
            li.innerHTML = '<span class="iplay"><font class="aname"></font><br/><font class="ainf"></font></span>';
            li.setAttribute("onclick", "playAudio(this);");
            hl.insertBefore(li, le.nextSibling);
            li.querySelector(".aname").innerText = entry.name;
            li.querySelector(".ainf").innerText = "...";
            li.entry = entry;
            me.updateInformation(li);
            // 设置空项不可见
            this.le.style.display = "none";
        },
        // 开始录音
    
        startRecord: function() {
            console.info("开始录音：");
            this.r = bsl.audio.getRecorder();
            if (this.r == null) {
                console.info("录音对象未获取");
                return;
            }
            this.r.record({
                filename: "_doc/audio/"
            }, function(p) {
                console.info("录音完成：" + p);
                bsl.io.resolveLocalFileSystemURL(p, function(entry) {
                    me.createItem(entry);
                }, function(e) {
                    console.info("读取录音文件错误：" + e.message);
                });
            }, function(e) {
                console.info("录音失败：" + e.message);
            });
            this.er.style.display = "block";
            this.t = 0;
            this.ri = setInterval(function() {
                this.t++;
                this.rt.innerText = timeToStr(this.t);
            }, 1000);
        },
        // 停止录音
        stopRecord: function() {
            this.er.style.display = "none";
            this.rt.innerText = "00:00:00";
            clearInterval(ri);
            this.ri = null;
            this.r.stop();
            this.w = null;
            this.r = null;
            this.t = 0;
        },
        // 清除历史记录
        cleanHistory: function() {
            this.hl.innerHTML = '<li id="empty" class="ditem-empty">无历史记录</li>';
            this.le = document.getElementById("empty");
            // 删除音频文件
            console.info("清空录音历史记录：");
            this.gentry.removeRecursively(function() {
                // Success
                console.info("操作成功！");
            }, function(e) {
                console.info("操作失败：" + e.message);
            });
        },
        // 获取录音历史列表
        updateHistory: function() {
            if (!gentry) {
                return;
            }
            var reader = gentry.createReader();
            reader.readEntries(function(entries) {
                for (var i in entries) {
                    if (entries[i].isFile) {
                        createItem(entries[i]);
                    }
                }
            }, function(e) {
                console.info("读取录音列表失败：" + e.message);
            });
        },
        // 获取录音文件信息
        updateInformation: function(li) {
            if (!li || !li.entry) {
                return;
            }
            var entry = li.entry;
            entry.getMetadata(function(metadata) {
                li.querySelector(".ainf").innerText = dateToStr(metadata.modificationTime);
            }, function(e) {
                console.info("获取文件\"" + entry.name + "\"信息失败：" + e.message);
            });
        },
        // 播放音频文件
        playAudio: function(li) {
            if (!li || !li.entry) {
                ouSet("无效的音频文件");
                return;
            }
            console.info("播放音频文件：" + li.entry.name);
            this.startPlay("_doc/audio/" + li.entry.name);
        },
        // 播放文件相关对象
        p: null,
        pt: null,
        pp: null,
        ps: null,
        pi: null,
        // 开始播放
        startPlay: function(url) {
            this.ep.style.display = "block";
            var L = this.pp.clientWidth;
            this.p = bsl.audio.createPlayer(url);
            this.p.play(function() {
                console.info("播放完成！");
                // 播放完成
                this.pt.innerText = timeToStr(d) + "/" + timeToStr(d);
                this.ps.style.webkitTransition = "all 0.3s linear";
                this.ps.style.width = L + "px";
                this.stopPlay();
            }, function(e) {
                console.info("播放音频文件\"" + url + "\"失败：" + e.message);
            });
            // 获取总时长
            var d = this.p.getDuration();
            if (!d) {
                this.pt.innerText = "00:00:00/" + timeToStr(d);
            }
            this.pi = setInterval(function() {
                if (!d) { // 兼容无法及时获取总时长的情况
                    d = this.p.getDuration();
                }
                var c = this.p.getPosition();
                if (!c) { // 兼容无法及时获取当前播放位置的情况
                    return;
                }
                this.pt.innerText = timeToStr(c) + "/" + timeToStr(d);
                var pct = Math.round(L * c / d);
                if (pct < 8) {
                    pct = 8;
                }
                this.ps.style.width = pct + "px";
            }, 1000);
        },
        // 停止播放
        stopPlay: function() {
            clearInterval(this.pi);
            this.pi = null;
            setTimeout(resetPlay, 500);
            // 操作播放对象
            if (this.p) {
                this.p.stop();
                this.p = null;
            }
        },
        // 重置播放页面内容
        resetPlay: function() {
            this.ep.style.display = "none";
            this.ps.style.width = "8px";
            this.ps.style.webkitTransition = "all 1s linear";
            this.pt.innerText = "00:00:00/00:00:00";
        },
        // 重写关闭
        // var _back = window.back;

        resetback: function() {
            // 停止播放
            if (this.ep.style.display == "block") {
                this.stopPlay();
            } else if (this.er.style.display == "block") {
                this.stopRecord();
            } else {
                window.history.go(-1);
            }
        },
        // window.back = resetback;

    });
    return view;
});
